import numpy as np
import matplotlib.pyplot as plt

from complex_PLM.PRNG import piecewise_logistic_map


def logistic_map(r, x):
    return r * x * (1 - x)

def generate_logistic_sequence(r, x0, num_iterations):
    sequence = [x0]
    for _ in range(num_iterations):
        x = sequence[-1]
        next_x = piecewise_logistic_map(x, r, 64)
        sequence.append(next_x)
    return sequence

def plot_bifurcation_diagram(r_values, x0, num_transient_iterations, num_iterations):
    fig, ax = plt.subplots(figsize=(8, 6))
    for r in r_values:
        transient_sequence = generate_logistic_sequence(r, x0, num_transient_iterations)
        sequence = generate_logistic_sequence(r, transient_sequence[-1], num_iterations)
        ax.scatter([r] * len(sequence), sequence, s=0.1, c="steelblue")
    plt.rcParams['font.sans-serif'] = ['SimSun']  # 设置中文字体为宋体
    plt.rcParams['font.serif'] = ['Times New Roman']  # 设置西文字体为Times New Roman

    # 解决负号'-'显示为方块的问题
    plt.rcParams['axes.unicode_minus'] = False
    ax.set_xlabel('μ',fontsize=24)
    ax.set_ylabel('x_n',fontsize=24)
    plt.xlim([0, 4.0])
    plt.ylim([0, 1.0])

    ax.set_xticks([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])
    ax.set_xticks([0,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0])
    plt.xticks(fontsize=24)
    plt.yticks(fontsize=24)
    # ax.set_title('Logistic Map Bifurcation Diagram')
    plt.show()

# 参数设置
r_values = np.linspace(0, 4.0, 1000)  # r的范围
x0 = 0.5  # 初始状态值
num_transient_iterations = 3000  # 瞬态迭代次数
num_iterations = 600  # 总迭代次数

# 生成并绘制分岔图
plot_bifurcation_diagram(r_values, x0, num_transient_iterations, num_iterations)
